<template>
    <view class="page bg-fff">
        <block v-if="faqList.length > 0">
            <block v-for="(item, num) in faqList" :key="num">
                <question-item :item="item" :index="num" @collectSucc="collectSuccess"
                    @thumbSucc="thumbSuccess" @deleteSucc="deleteSuccess"></question-item>
            </block>
            <up-loadmore :status="loadingType" margin-top="30" />
        </block>

        <up-empty text="暂无数据" mode="list" marginTop="100" v-if="faqList.length === 0 && loadingType === 'nomore'"></up-empty>


        <view class="questionBtn flex bg-theme boxShow col-fff font12" @click="toForumForm">
            <text class="iconQuestion bg"></text>
            <text class="top-3">我要提问</text>
        </view>

        <up-gap height="30"></up-gap>

        <tabbar></tabbar>
    </view>
</template>

<script setup>
import QuestionItem from './components/question-item.vue';
import { ref } from 'vue';
import { useUserInfoStore, useIndexStore } from '@/store/index';
import { onShow, onLoad, onReachBottom, onPullDownRefresh, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { checkLogin, checkUserInfo } from '@/common/common';
import { getFaqList } from '@/common/api/forum';

const userInfoStore = useUserInfoStore();
const indexStore = useIndexStore();

//首次加载
const isFirstLoad = ref(true);

let faqList = ref([]);
let loadingType = ref('loadmore');
let next = ref('');

onShow(async () => {
    if(!isFirstLoad.value || indexStore.updateForum) {
        await init();
    }

    //延迟1秒再验证验证是否填写上周数据
	setTimeout(async () => {
		await userInfoStore.checkLastWeekVisitData();

		if(userInfoStore.showStatisticsForm) {
			uni.showModal({
				title: '提示',
				showCancel: false,
				content: '检测到您上周未提交到访数据，请及时提交',
				success: (res) => {
					if(res.confirm) {
						uni.navigateTo({
							url: `/pages/my/statistics/form/index?startDate=${userInfoStore.statisticsFormObj.start_time}&endDate=${userInfoStore.statisticsFormObj.end_time}`
						})
					}
				}
			})
		}
	}, 1500)
});

onLoad(() => {
	uni.$check_and_login(function() {
        if(isFirstLoad.value) {
            init();
        }
    })
});

onPullDownRefresh(async () => {
    await init();
});

onReachBottom(async () => {
    await loadFaqList(false);
});

// 分享到好友
onShareAppMessage(() => {
    return {
        title: '新房超市',
        path: `/pages/tabBar/home/index?puid=${userInfoStore.userInfo.id}`,
        imageUrl: '',
    }
})

// 分享到朋友圈
onShareTimeline(() => {
    return {
        title: '新房超市',
        query: `puid=${userInfoStore.userInfo.id}`,
        imageUrl: '',
    }
})

// 初始化
async function init() {
    isFirstLoad.value = false;
    indexStore.setUpdateForum(false);
    await userInfoStore.checkUserInfo();//验证用户信息,如果没有就获取并且更新
    await loadFaqList(true);
}

// 获取问答列表
async function loadFaqList(isRefresh = false) {
    if (isRefresh) {
		loadingType.value = 'loadmore';
		next.value = '';
        setTimeout(() => {
			uni.stopPullDownRefresh()
		}, 500)
	}
    if (loadingType.value === 'loading' || loadingType.value === 'nomore') return;
    loadingType.value = 'loading';
    let url = next.value ? next.value : `/product/mall/qa/v2/list/tag`;
    try {
        let { status, detail } = await getFaqList(url);
        if (status !== 0) {
            uni.showToast({
                title: detail,
                icon: 'none'
            });
            return;
        }
        if (isRefresh) {
			faqList.value = detail.results;
		} else {
			faqList.value.push(...detail.results);
		}
        next.value = detail.next;
        loadingType.value = detail.next ? 'loadmore' : 'nomore';
    } catch (error) {
        console.log(error);
    }
}

// 我要提问
function toForumForm() {
    if(!checkLogin()) {
        uni.navigateTo({
            url: '/pages/login/login'
        })
        return
    }
    if(!checkUserInfo()) {
        uni.navigateTo({
            url: `/pages/login/user-info-form`
        })
        return
    }
    uni.navigateTo({
        url: '/pages/tools/question/question-form'
    });
}

// 收藏成功
function collectSuccess(id) {
    let findItem = faqList.value.find(item => item.id === id);
    if(findItem) {
        findItem.store ? findItem.store_num-- : findItem.store_num++;
        findItem.store = !findItem.store;
    }
}

// 点赞成功
function thumbSuccess(id) {
    let findItem = faqList.value.find(item => item.id === id);
    if(findItem) {
        findItem.love ? findItem.like_num-- : findItem.like_num++;
        findItem.love = !findItem.love;
    }
}

// 删除成功
function deleteSuccess(id) {
    faqList.value = faqList.value.filter(item => item.id !== id);
}
</script>

<style lang="scss" scoped>
.page {
    min-height: 100vh;
    position: relative;

    .questionBtn {
        position: fixed;
        bottom: 200rpx;
        right: 30rpx;
        z-index: 10;
        flex-direction: column;
        width: 150rpx;
        height: 150rpx;
        border-radius: 50%;

        .iconQuestion {
            width: 70rpx;
            height: 60rpx;
            background-image: url("https://image.srea.org.cn/xcx/icon/faq-question-icon.png");
        }
    }
}
</style>
